package com.knife.blog.web.action;

import java.io.File;
import java.util.Iterator;

import com.knife.util.CommUtil;
import com.knife.util.FileUtil;
import com.knife.web.Globals;
import com.knife.web.Module;
import com.knife.web.Page;
import com.knife.web.WebForm;

import org.apache.commons.fileupload.FileItem;
import org.apache.log4j.Logger;

public class CommUploadAction extends BaseCmdAction {
	private static final Logger logger = (Logger) Logger
			.getLogger(CommUploadAction.class.getName());

	public Object doBefore(WebForm form, Module module) {
		blog = userService.getUserBlog(this.getCurrentUser(form).getUserName());
		return super.doBefore(form, module);
	}

	public Page doInit(WebForm form, Module module) {
		// TODO Auto-generated method stub
		String subCommand = CommUtil.null2String(form.get("subCommand"));
		if (subCommand.equals("NewsContent")) {
			String Types = CommUtil.null2String(form.get("types"));
			Iterator it = form.getFileElement().keySet().iterator();
			if (it.hasNext()) {
				String fieldName = (String) it.next();
				FileItem file = (FileItem) form.getFileElement().get(fieldName);
				String clientName = file.getName();

			} else {
				logger.error("上传失败！");
			}
		}
		return module.findPage(module.getDefaultPage());
	}

	public Page doImgDialog(WebForm form, Module module) {
		Iterator it = form.getFileElement().keySet().iterator();
		if (it.hasNext()) {
			String fieldName = (String) it.next();
			FileItem file = (FileItem) form.getFileElement().get(fieldName);
			String clientName = file.getName();
			if (!FileUtil.isAttacheFile(clientName)
					&& !FileUtil.isImgageFile(clientName)) {
				form.addResult("msg", "只能上传图片文件及附件文件！");
				return module.findPage("dialog");
			}
			if (FileUtil.isImgageFile(clientName))
				form.addResult("isImg", "true");
			String tmpFile = uploadFile(file);
			if (!tmpFile.equals("")) {
				// System.out.println(tmpFile);
				form.addResult("fileName", tmpFile);
				form.addResult("clientName", clientName.substring(clientName
						.lastIndexOf("\\") + 1));
			}
		}
		return module.findPage("dialog");
	}

	public String uploadFile(FileItem file) {
		String ret = null;
		String clientName = file.getName();
		FileUtil.isImgageFile(clientName);
		if (file != null) {
			String filePath = Globals.APP_BASE_DIR + "/upfile/blog/"
					+ blog.getCid() + "/";
			File fdir = new File(filePath);
			if (!fdir.exists())
				fdir.mkdirs();
			try {
				String fileName = clientName.substring(clientName
						.lastIndexOf(File.separator) + 1);
				file.write(new File(filePath + fileName));
				ret = "/upfile/blog/" + blog.getCid() + "/" + fileName;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return ret;
	}
}
